<?php

defined('SYSPATH') or die('Access error!');

/**
 * 用户的账户处理基类
 */
class Model_User_Account extends Model
{

    protected $to_user_id;          //接收方
    protected $from_user_id;        //授予方  系统为0
    protected $current_account;     //用户的当前账户（接收方）
    protected $account;             //接收多少
    protected $operation;           //是增加或者是减少
    protected $message;             //记录日志内容
    protected $time;                //多久后再次可以提交
    protected $add_type;            //是日志,是问题，还是认证等等。。。。
    protected $today_nums;          //某一个方式的当天次数 和time关联
    protected $detail_id;           //例如：某个具体日志的id
    protected $type;                //是积分 还是经验等
    protected static $all_account_config = array();      //账户配置
    //账户所需要的配置文件
    protected $account_config = array();  //账户配置
    protected $account_setting = array(); //账户设置

    public static function factory($table, $db = NULL)
    {
        self::$all_account_config = Core::config('account');
        $class = 'Model_' . $table;
        return new $class($db, 'user_account');
    }

    /**
     *  获取对应账户的配置文件
     * @param type $key
     * @return type
     */
    public function get_account_config($key)
    {
        if (Arr::validate_arr(self::$all_account_config[$key]))
        {
            $this->account_config = self::$all_account_config[$key];
            return $this->account_config;
        }
        return array();
    }

    /**
     *  根据id号获取用户的账户设置
     * @param type $id
     * @return type
     */
    public function get_account_setting($id)
    {
        $account_setting = Model_Setting::factory('setting')->get_sub_setting($id);
        $this->account_setting = Arr::setkey('code', $account_setting);
        return Arr::validate_arr($this->account_setting) ? $this->account_setting : array();
    }

    /**
     * 处理积分的配置和系统的设置
     * @param type $code
     * @return type
     */
    public function handle_account_config_setting($code)
    {

        $code_key = $code;
        if (Arr::validate_arr($code))
        {
            $code_key = key($code);
        }
        $this->add_type = Arr::recursion_get_key($this->account_config, $code_key);
        $config = Arr::recursion_get_value($this->account_config, $code_key);
        if (count($config) > 0)
        {
            if (Arr::validate_arr($code))
            {
                $config['account'] = current($code);
            }
            else
            {
                if (isset($this->account_setting[$code_key]['value']))
                {
                    $config['account'] = $this->account_setting[$code_key]['value'];
                }
            }
        }
        return $config;
    }

    /**
     *  根据用户的id得到对应的信息
     * @param type $user_id
     * @param type $params
     * @return type
     */
    public function get_user_account($user_id, $params = '')
    {
        $data = $this->get_row(array('user_id' => $user_id), $params);
        if (count($data) > 0)
        {
            return $data;
        }
        return array();
    }

    /**
     * 生成用户的个人账户资料（有待改进 要后台初始化账户信息）
     * @param type $user_id
     */
    public function create_user_account($user_id)
    {
        $data = array();
        $data['user_id'] = $user_id;
        $data['add_time'] = Date::get_time();
        $data['amount'] = '0.00';
        $data['points'] = 0;
        $data['experience'] = 0;
        $this->insert($data);
    }

    /**
     * 根据type  即：积分 经验 rmb获取日志列表
     * @param type $type
     * @return type
     */
    public function get_log_list($type)
    {
        $where = " WHERE  ua.type = '" . $type . "'" .
                " AND ua.user_id=" . Session::instance()->get_detail('user', 'id') .
                ' ORDER BY ua.id DESC';

        $sql = ' SELECT ua.*,u.username ' .
                " FROM " . $this->db->get_table('user_accountlog') . " AS ua " .
                "LEFT JOIN " . $this->db->get_table('user') . " AS u ON ua.user_id = u.id" . $where;
        $data = $this->get_page_list($sql, 10);
        return count($data) > 0 ? $data : array();
    }

    /**
     * 更新用户账户
     * @return boolean
     */
    public function update_account()
    {
        //处理用户积分----增减操作
        $after_account = $this->handle_user_account();
        
  
        //更新用户的账户信息
        if ($this->update(array($this->type => $after_account), array('user_id' => $this->to_user_id)))
        {
            $user_detail = Session::instance()->get('user');
            if (Arr::validate_arr($user_detail))
            {
                $user_detail[$this->type] = $after_account;
                Session::instance()->set('user', $user_detail);
            }
            return TRUE;
        }
        return FALSE;
    }

    /**
     * 处理用户的积分操作 USER_ACCOUNT_POINTS_ADD---增加     USER_ACCOUNT_POINTS_SUBTRACT--减少
     * @return account
     */
    public function handle_user_account()
    {
        if ($this->operation == USER_ACCOUNT_ADD)
        {
            return intval($this->current_account + $this->account);
        }
        elseif ($this->operation == USER_ACCOUNT_SUB)
        {
            return intval($this->current_account - $this->account);
        }
    }

    /**
     * 记录到账户日志
     */
    public function update_account_log()
    {
        $data = array();
        $data['user_id'] = $this->to_user_id;

        //根据用户的id获取用户名
        $data['username'] = Model_User::factory('user')->get_var(array('id' => $data['user_id']), 'username');

        $data['from_userid'] = $this->from_user_id;
        $data['message'] = $this->message;
        $data['detail_id'] = $this->detail_id;
        $data['operation'] = $this->operation;
        $data['type'] = $this->type;
        $data['add_type'] = $this->add_type;
        $data['add_time'] = Date::get_time();
        $data['ip'] = URL::get_ip();
        $data['account'] = $this->account;

        if ($this->insert($data, $this->db->get_table('user_accountlog')))
        {
            return TRUE;
        }
    }

    /**
     *  检查用户的账号信息
     * @param type $account
     * @param type $account_type
     * @param type $user_id
     * @return type
     */
    public function checke_user_account($account, $account_type, $user_id = '')
    {
        if (empty($user_id))
        {
            $user_id = Session::instance()->get_detail('user', 'id');
        }
        $current_account = $this->get_user_account($user_id, 'amount,points');
        $account = array('account' => $account, 'type' => $account_type);
        return $this->validate_account($current_account, $account);
    }

    //配合checke_user_account 验证用户的账户
    public function validate_account($current_account, $account)
    {
        switch ($account['type'])
        {
            case 'points':
                return ($current_account['points'] - $account['account']) >= 0 ? TRUE : FALSE;
                break;
            case 'amount':
                return ($current_account['amount'] - $account['amount']) >= 0 ? TRUE : FALSE;
                break;
            default:
                return TRUE;
                break;
        }

        return FALSE;
    }

}